import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution4 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode dum = new ListNode(0);
        dum.next = head;
        int count = 0;
        while(head != null) {
            count ++;
            head = head.next;
        }
        count = count / k;
        int i = k;
        ListNode pre = dum;
        ListNode cur = pre.next;
        while(count > 0) {
            count--;
            i = k;
            while(i > 1) {
                i--;
                ListNode curNext = cur.next;
                cur.next = curNext.next;
                curNext.next = pre.next;
                pre.next = curNext;
            }
            pre = cur;
            cur = cur.next;
        }
        return dum.next;
    }
}